import api from '@/api/api'

export interface AuthFeatureConfig {
  auth_required: boolean
  allow_register: boolean
  anonymous_user_id: string
}

const defaultConfig: AuthFeatureConfig = {
  auth_required: true,
  allow_register: false,
  anonymous_user_id: 'anonymous'
}

let cachedConfig: AuthFeatureConfig | null = null
let inflightPromise: Promise<AuthFeatureConfig> | null = null

const normalizeConfig = (config: Partial<AuthFeatureConfig> | undefined): AuthFeatureConfig => {
  if (!config) {
    return { ...defaultConfig }
  }
  return {
    auth_required: typeof config.auth_required === 'boolean' ? config.auth_required : defaultConfig.auth_required,
    allow_register: typeof config.allow_register === 'boolean' ? config.allow_register : defaultConfig.allow_register,
    anonymous_user_id: config.anonymous_user_id || defaultConfig.anonymous_user_id
  }
}

export const loadAuthConfig = async (force = false): Promise<AuthFeatureConfig> => {
  if (cachedConfig && !force) {
    return cachedConfig
  }
  if (!inflightPromise) {
    inflightPromise = api
      .get<AuthFeatureConfig>('/v1/auth/config')
      .then((response) => {
        cachedConfig = normalizeConfig(response.data)
        return cachedConfig
      })
      .catch(() => {
        cachedConfig = { ...defaultConfig }
        return cachedConfig
      })
      .finally(() => {
        inflightPromise = null
      })
  }
  return inflightPromise
}

export const getCachedAuthConfig = (): AuthFeatureConfig => {
  return cachedConfig ?? defaultConfig
}

export const resetAuthConfigCache = () => {
  cachedConfig = null
}

